/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program.utilities;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;

/**
 * Class to rotate the delivered image in the delivered rotation angle
 * 
 *Responsible: Bernhard
 */
public class ImageRotator {

    public static Image rotateImage(BufferedImage inputImage, int rotAngle) {

        int X = 0, Y = 0;

        if ((rotAngle == 0) || (rotAngle == 180) || (rotAngle == 360)) {
            X = inputImage.getWidth(null);
            Y = inputImage.getHeight(null);
        } else {
            X = inputImage.getHeight(null);
            Y = inputImage.getWidth(null);
        }

        BufferedImage sourceBI = new BufferedImage(X, Y, BufferedImage.TYPE_INT_RGB);

        AffineTransform at = new AffineTransform();

        // rotate around image center
        at.rotate(Math.toRadians(rotAngle), (sourceBI.getWidth() / 2), (sourceBI.getHeight() / 2));

        /**
         * translate to make sure the rotation doesn't cut off any image data
         */
        AffineTransform translationTransform;
        translationTransform = findTranslation(at, sourceBI, rotAngle);
        at.preConcatenate(translationTransform);


        Graphics2D g = (Graphics2D) sourceBI.getGraphics();
        g.setTransform(at);
        g.drawImage(inputImage, 0, 0, null);


        return ImageUtilities.convertBufferedImageToImage(sourceBI);
    }

    /**
     * find proper translations to keep rotated image correctly displayed
     */
    private static AffineTransform findTranslation(AffineTransform at, BufferedImage bi, int rotAngle) {
        Point2D p2din, p2dout;
        double ytrans, xtrans = 0.0;

        AffineTransform tat = new AffineTransform();

        if (rotAngle == 180) {
            p2din = new Point2D.Double(0, bi.getHeight());
        } else {
            p2din = new Point2D.Double(0.0, 0.0);
        }

        p2dout = at.transform(p2din, null);

        if (rotAngle == 270) {
            xtrans = p2dout.getX();
            ytrans = xtrans;
        } else {
            ytrans = p2dout.getY();
            xtrans = ytrans;
        }
        tat.translate(-xtrans, -ytrans);

        return tat;
    }
}